package com.lnlyj.media.data.load;

import com.lnlyj.media.LnlyjSelector;
import com.lnlyj.media.data.AlbumItem;
import com.lnlyj.media.data.MediaGroup;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * wanglei 2020-04-18
 */
public class LoadManager {

    private List<AlbumItem> albumItems = new ArrayList<>();
    private Map<QueryConfig, List<MediaGroup>> mediaGroups = new HashMap<>();
    private AlbumLoader albumLoader;
    private MediaLoader mediaLoader;


    private static class Instance {
        public static LoadManager manager = new LoadManager();
    }

    public static LoadManager getInstance() {
        return Instance.manager;
    }

    private LoadManager() {

    }

    public List<AlbumItem> loadAlbumData(AlbumLoader.OnAlbumLoaderCallback callback) {
        albumLoader = new AlbumLoader(LnlyjSelector.getInstance().getApplication().getContentResolver());
        albumLoader.setCallback(list -> {

            if (!albumItems.equals(list)) {
                albumItems.clear();
                albumItems.addAll(list);
                if (callback != null) {
                    callback.onAlbumLoaderFinish(albumItems);
                }
            }
        });

        albumLoader.execute();
        return this.albumItems;
    }

    public List<MediaGroup> loadMediaData(QueryConfig config, MediaLoader.OnMediaLoaderCallback callback) {
        List<MediaGroup> groups = mediaGroups.remove(config);

        mediaLoader = new MediaLoader(LnlyjSelector.getInstance().getApplication().getContentResolver(), config);
        mediaLoader.setCallback(list -> {
            mediaGroups.put(config, list);

            if (!list.equals(groups) && callback != null) {
                callback.onLoaderFinish(list);
            }
        });
        mediaLoader.execute();
        return groups;
    }

    public void clearCache() {
        albumItems.clear();
        mediaGroups.clear();
    }
}
